{% extends "base.html" %}

{% block title %}{{ page_title }} - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    .balance-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 15px;
        color: white;
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    }

    .balance-amount {
        font-size: 2.5rem;
        font-weight: bold;
        margin: 1rem 0;
    }

    .balance-subtitle {
        font-size: 1.1rem;
        opacity: 0.9;
        margin-bottom: 0.5rem;
    }

    .quick-stats {
        background: rgba(255,255,255,0.1);
        border-radius: 10px;
        padding: 1rem;
        margin-top: 1.5rem;
    }

    .stat-item {
        text-align: center;
        padding: 0.5rem;
    }

    .stat-value {
        font-size: 1.5rem;
        font-weight: bold;
        display: block;
    }

    .stat-label {
        font-size: 0.9rem;
        opacity: 0.8;
    }

    .transaction-item {
        border-left: 4px solid #dee2e6;
        padding: 1rem;
        margin-bottom: 1rem;
        background: #f8f9fa;
        border-radius: 0 5px 5px 0;
        transition: all 0.3s ease;
    }

    .transaction-item:hover {
        background: #e9ecef;
        transform: translateX(5px);
    }

    .transaction-item.income {
        border-left-color: #28a745;
    }

    .transaction-item.expense {
        border-left-color: #dc3545;
    }

    .transaction-amount {
        font-weight: bold;
        font-size: 1.1rem;
    }

    .amount-positive {
        color: #28a745;
    }

    .amount-negative {
        color: #dc3545;
    }

    .chart-container {
        background: white;
        border-radius: 10px;
        padding: 1.5rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
    }

    .action-buttons {
        display: flex;
        gap: 1rem;
        margin-top: 1.5rem;
        flex-wrap: wrap;
    }

    .btn-primary {
        background: linear-gradient(45deg, #007bff, #0056b3);
        border: none;
        padding: 0.75rem 1.5rem;
        border-radius: 25px;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,123,255,0.3);
    }

    .btn-outline-primary {
        border: 2px solid #007bff;
        border-radius: 25px;
        padding: 0.75rem 1.5rem;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .btn-outline-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,123,255,0.2);
    }

    .status-badge {
        padding: 0.25rem 0.75rem;
        border-radius: 15px;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .status-active {
        background: #d4edda;
        color: #155724;
    }

    .status-frozen {
        background: #f8d7da;
        color: #721c24;
    }

    @media (max-width: 768px) {
        .balance-amount {
            font-size: 2rem;
        }

        .action-buttons {
            flex-direction: column;
        }

        .action-buttons .btn {
            width: 100%;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="page-title">
                <i class="fas fa-wallet me-2"></i>账户余额
            </h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    {% if current_user.role == 'coach' %}
                    <li class="breadcrumb-item"><a href="{{ url_for('dashboard.coach') }}">首页</a></li>
                    {% else %}
                    <li class="breadcrumb-item"><a href="{{ url_for('dashboard.student') }}">首页</a></li>
                    {% endif %}
                    <li class="breadcrumb-item active">账户余额</li>
                </ol>
            </nav>
        </div>
    </div>

    <!-- 账户余额卡片 -->
    <div class="row">
        <div class="col-lg-8">
            <div class="balance-card">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="balance-subtitle">当前余额</div>
                        <div class="balance-amount">
                            ¥{{ "%.2f"|format(account_summary.balance) }}
                        </div>
                        <div class="row mt-3">
                            <div class="col-12 text-center">
                                <small class="balance-subtitle">可用余额</small>
                                <div class="h5 mb-0">¥{{ "%.2f"|format(account_summary.available_balance) }}</div>
                            </div>
                        </div>

                        <!-- 账户状态 -->
                        <div class="mt-3">
                            <span class="status-badge status-active">
                                <i class="fas fa-check-circle me-1"></i>账户正常
                            </span>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="quick-stats">
                            <div class="row text-center">
                                <div class="col-6">
                                    <div class="stat-item">
                                        <span class="stat-value">{{ account_summary.transaction_count_30d }}</span>
                                        <small class="stat-label">30天交易</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="stat-item">
                                        <span class="stat-value">¥{{ "%.0f"|format(account_summary.total_expense_30d) }}</span>
                                        {% if current_user.role == 'coach' %}
                                        <small class="stat-label">30天收入</small>
                                        {% else %}
                                        <small class="stat-label">30天消费</small>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    {% if current_user.role == 'student' %}
                    <a href="{{ url_for('accounts.recharge') }}" class="btn btn-light btn-lg">
                        <i class="fas fa-plus-circle me-2"></i>立即充值
                    </a>
                    {% endif %}
                    <a href="{{ url_for('accounts.transactions') }}" class="btn btn-outline-light btn-lg">
                        <i class="fas fa-list me-2"></i>交易记录
                    </a>
                </div>
            </div>
        </div>

        <!-- 快速信息面板 -->
        <div class="col-lg-4">
            <!-- 待支付预约 (仅学员) -->
            {% if current_user.role == 'student' and account_summary.pending_amount > 0 %}
            <div class="alert alert-warning">
                <h6 class="alert-heading">
                    <i class="fas fa-exclamation-triangle me-2"></i>待支付预约
                </h6>
                <p class="mb-2">您有待支付的预约费用</p>
                <div class="h5 text-warning">¥{{ "%.2f"|format(account_summary.pending_amount) }}</div>
                <hr>
                <p class="mb-0">
                    <a href="{{ url_for('student_reservations.index') }}" class="alert-link">
                        查看待支付预约 <i class="fas fa-arrow-right"></i>
                    </a>
                </p>
            </div>
            {% endif %}

            <!-- 最近交易 -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-history me-2"></i>最近交易
                    </h6>
                    <a href="{{ url_for('accounts.transactions') }}" class="btn btn-sm btn-outline-primary">
                        查看全部
                    </a>
                </div>
                <div class="card-body p-0">
                    {% if recent_transactions %}
                        {% for transaction in recent_transactions %}
                        <div class="transaction-item {{ 'income' if transaction.amount > 0 else 'expense' }}">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="fw-medium">{{ transaction.description }}</div>
                                    <small class="text-muted">
                                        <i class="fas fa-clock me-1"></i>
                                        {{ transaction.created_at.strftime('%m-%d %H:%M') }}
                                    </small>
                                </div>
                                <div class="transaction-amount {{ 'amount-positive' if transaction.amount > 0 else 'amount-negative' }}">
                                    {{ '+' if transaction.amount > 0 else '' }}¥{{ "%.2f"|format(transaction.amount) }}
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center py-4 text-muted">
                            <i class="fas fa-receipt fa-2x mb-3"></i>
                            <p>暂无交易记录</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 月度统计概览 -->
    {% if monthly_stats and not monthly_stats.get('error') %}
    <div class="row mt-4">
        <div class="col-12">
            <div class="chart-container">
                <h5 class="mb-4">
                    <i class="fas fa-chart-line me-2"></i>本月消费概览
                </h5>

                <div class="row text-center mb-4">
                    <div class="col-md-3">
                        <div class="h4 text-success">¥{{ "%.2f"|format(monthly_stats.total_income) }}</div>
                        <small class="text-muted">本月收入</small>
                    </div>
                    <div class="col-md-3">
                        <div class="h4 text-danger">¥{{ "%.2f"|format(monthly_stats.total_expense) }}</div>
                        <small class="text-muted">本月支出</small>
                    </div>
                    <div class="col-md-3">
                        <div class="h4 text-primary">{{ monthly_stats.total_transactions }}</div>
                        <small class="text-muted">交易笔数</small>
                    </div>
                    <div class="col-md-3">
                        <div class="h4 text-info">¥{{ "%.2f"|format(monthly_stats.average_per_transaction) }}</div>
                        <small class="text-muted">平均金额</small>
                    </div>
                </div>

                {% if monthly_stats.by_type %}
                <div class="row">
                    <div class="col-md-6">
                        <canvas id="typeChart" height="200"></canvas>
                    </div>
                    <div class="col-md-6">
                        <canvas id="trendChart" height="200"></canvas>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    {% endif %}

    <!-- 快捷操作 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-bolt me-2"></i>快捷操作
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <a href="{{ url_for('accounts.recharge') }}" class="btn btn-outline-primary w-100">
                                <i class="fas fa-plus-circle mb-2 d-block"></i>
                                账户充值
                            </a>
                        </div>
                        <div class="col-md-4">
                            <a href="{{ url_for('accounts.transactions') }}" class="btn btn-outline-info w-100">
                                <i class="fas fa-list mb-2 d-block"></i>
                                交易记录
                            </a>
                        </div>
                        <div class="col-md-4">
                            <a href="{{ url_for('student_reservations.create') }}" class="btn btn-outline-success w-100">
                                <i class="fas fa-calendar-plus mb-2 d-block"></i>
                                立即预约
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    // 初始化图表
    {% if monthly_stats and monthly_stats.by_type %}
    initTypeChart();
    {% endif %}

    {% if monthly_stats and monthly_stats.by_date %}
    initTrendChart();
    {% endif %}

    // 实时更新余额
    updateBalance();
    setInterval(updateBalance, 30000); // 每30秒更新一次
});

// 交易类型分布图
function initTypeChart() {
    const ctx = document.getElementById('typeChart');
    if (!ctx) return;

    const typeData = {{ monthly_stats.by_type | tojson }};
    const labels = [];
    const amounts = [];
    const colors = [
        '#28a745', '#dc3545', '#ffc107', '#007bff', '#6c757d', '#17a2b8'
    ];

    Object.keys(typeData).forEach(type => {
        labels.push(getTypeDisplayName(type));
        amounts.push(parseFloat(typeData[type].amount));
    });

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: amounts,
                backgroundColor: colors.slice(0, labels.length),
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '消费类型分布'
                },
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

// 消费趋势图
function initTrendChart() {
    const ctx = document.getElementById('trendChart');
    if (!ctx) return;

    const dateData = {{ monthly_stats.by_date | tojson }};
    const dates = Object.keys(dateData).sort();
    const amounts = dates.map(date => parseFloat(dateData[date]));

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates.map(date => {
                const d = new Date(date);
                return (d.getMonth() + 1) + '/' + d.getDate();
            }),
            datasets: [{
                label: '日消费金额',
                data: amounts,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '30天消费趋势'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toFixed(2);
                        }
                    }
                }
            }
        }
    });
}

// 实时更新余额
function updateBalance() {
    $.get('{{ url_for("accounts.api_get_balance") }}')
        .done(function(response) {
            if (response.success) {
                // 更新余额显示，添加动画效果
                const balanceElement = $('.balance-amount');
                balanceElement.fadeOut(200, function() {
                    $(this).text('¥' + response.data.balance.toFixed(2)).fadeIn(200);
                });

                // 更新可用余额
                const availableElement = balanceElement.parent().find('.h5').first();
                availableElement.fadeOut(200, function() {
                    $(this).text('¥' + response.data.available_balance.toFixed(2)).fadeIn(200);
                });
            }
        })
        .fail(function() {
            console.log('更新余额失败');
        });
}

// 获取交易类型显示名称
function getTypeDisplayName(type) {
    const typeNames = {
        'recharge': '充值',
        'reservation': '预约扣费',
        'refund': '退款',
        'penalty': '违约金',
        'freeze': '余额冻结',
        'unfreeze': '余额解冻'
    };
    return typeNames[type] || type;
}

// 页面加载动画
window.addEventListener('load', function() {
    $('.balance-card').hide().fadeIn(800);
    $('.card').each(function(index) {
        $(this).delay(index * 200).fadeIn(600);
    });
});
</script>
{% endblock %}